import { memo, useMemo } from 'react';
import type { FC, PropsWithChildren } from 'react';
import { Navigate, useLocation } from 'react-router-dom';
import { message } from 'antd';
import { userStore } from '@/store/userStore';
import { useRecoilValue } from 'recoil';

const AdminWrapper: FC<PropsWithChildren<{}>> = ({ children }) => {
  const location = useLocation();
  const user = useRecoilValue(userStore);
  const redirect = '/';
  const isAdmin = useMemo(() => {
    return location.pathname.includes('/admin') && user.role !== 1;
  }, [location, user]);
  if (isAdmin) {
    message.warn('权限不足！');
  }
  return isAdmin ? <>{children}</> : <Navigate to={redirect} replace />;
};

export default memo(AdminWrapper);
